package org.rcy.ruicingmarket.login;

import com.fasterxml.jackson.databind.ObjectMapper;
import org.rcy.framework.api.entity.StatusCode;
import org.rcy.framework.cache.redis.CommonCache;
import org.rcy.framework.security.authentication.AuthenticationToken;
import org.rcy.framework.security.stateless.StatelessLoginSuccessHandler;
import org.rcy.ruicingmarket.exception.CaptchaException;
import org.rcy.ruicingmarket.cache.OssCacheGroup;
import org.rcy.ruicingmarket.common.utils.TokenUtils;
import org.rcy.ruicingmarket.oss.user.OssUserDao;
import org.rcy.ruicingmarket.oss.user.OssUser;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.web.authentication.AuthenticationFailureHandler;
import org.springframework.security.web.authentication.logout.LogoutHandler;
import org.springframework.stereotype.Component;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

/**
 * @author 吴康桥
 * @Description
 * @date 2022/10/31 16:58
 */

@Component
public class OssLoginHandler extends StatelessLoginSuccessHandler implements AuthenticationFailureHandler, LogoutHandler {

	protected final Logger logger = LoggerFactory.getLogger(getClass());

	@Value("${oss.token.encryptkey:rcy}")
	private String encryptkey;
	@Autowired
	private OssUserDao userDao;
	@Autowired
	private CommonCache commonCache;
	@Autowired
	private ObjectMapper objectMapper;

	@Override
	protected void successHandle(HttpServletRequest request, HttpServletResponse response, AuthenticationToken authentication) throws Exception {
		response.setContentType("application/json;charset=UTF-8");
		response.setHeader("Cache-Control", "no-cache");
		response.setHeader("Expires", "0");
		response.setHeader("Pragma", "No-cache");
		PrintWriter out = response.getWriter();
		HashMap<String, Object> map = new HashMap<String, Object>();
		OssUser user = (OssUser) authentication.getPrincipal();
		user.setLastLoginTime(new Date());
		String ossToken = TokenUtils.getToken(user.getId(),encryptkey);
		commonCache.cache(OssCacheGroup.OSS_USER, ossToken,user.getAccount(),3600);
		userDao.update(user,true);
		map.put("token",ossToken);
		map.put("code","20000");
		map.put("flag",true);
		objectMapper.writeValue(out, map);
	}

	@Override
	public void onAuthenticationFailure(HttpServletRequest request, HttpServletResponse response, AuthenticationException e) throws IOException, ServletException {
		if(null != e){
			Map<String, Object> map = new HashMap();
			//返回登录错误消息
			response.setContentType("application/json;charset=UTF-8");
			PrintWriter out = response.getWriter();
			response.setHeader("Cache-Control", "no-cache");
			response.setHeader("Expires", "0");
			response.setHeader("Pragma", "No-cache");
			map.put("flag",false);
			if (e instanceof CaptchaException){
				map.put("code", StatusCode.VALIDATECODEERROR.getValue());
				map.put("message", StatusCode.VALIDATECODEERROR.getReasonPhrase());
				objectMapper.writeValue(out, map);
				return;
			}
			map.put("code","20002");
			map.put("message", StatusCode.USERANDPASSWORDERROR.getReasonPhrase());
			objectMapper.writeValue(out, map);
		}
	}

	@Override
	public void logout(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Authentication authentication) {
		String ossInnerToken = httpServletRequest.getHeader("ossInnerToken");
		Object userStatus1 = commonCache.getData(OssCacheGroup.OSS_USER, ossInnerToken);
		if(userStatus1 != null) {
			commonCache.remove(OssCacheGroup.OSS_USER,ossInnerToken);
		}
	}
}
